/**
 * Created by Alice on 2016/9/22 0022
 */

var planUid = utils.get_url_param("planUid");
var ip = null;
var channel = utils.get_url_param("channel");	//通道号
var videoNum = utils.get_url_param("videonum");	//录像号
var _data;//获取播放视频列表数据
var now_video = utils.get_url_param('vlcCourtUid');
var url_data = [];//存储所有的播放地址
var now_url = null;//当前播放地址
var record_casename = null;
var record_archives = null;
$(function () {
    $("#imageLoad").attr("href", r.base_path + 'views/major/image_video_load.html?court=' + r.court_id);
    // if (!planId) {
    //     $("#title").html('&nbsp;暂无案件信息');
    // } else {
    //     //案件信息
    //     // getCaseInfoByIdForToday(planId);
    // }
    //获取笔录信息
    getCourtrecForId();
    $("#_nav_court_info").click(function () {
        $("#_nav_court_p").attr("class", "");
        $("#_nav_court_note").attr("class", "");
        $("#_nav_court_info").attr("class", "active");
        $("#_court_info").show();
        // $("#_court_case").hide();
        $("#_court_note").hide();
        $("#_nav_court_note_down").hide();
    });
    $("#_nav_court_note").click(function () {
        $("#_nav_court_info").attr("class", "");
        $("#_nav_court_p").attr("class", "");
        $("#_nav_court_note").attr("class", "active");
        $("#_court_info").hide();
        // $("#_court_case").hide();
        $("#_court_note").show();
        $("#_nav_court_note_down").show();
    });
    $("#_nav_court_p").click(function () {
        $("#_nav_court_p").attr("class", "active");
        $("#_nav_court_note").attr("class", "");
        $("#_nav_court_info").attr("class", "");
        $("#_court_info").hide();
        // $("#_court_case").show();
        $("#_court_note").hide();
    });
    if (navigator.appName.indexOf("Microsoft Internet") == -1) {
        onVLCPluginReady()
    }
    else if (document.readyState == 'complete') {
        onVLCPluginReady();
    }
    else {
        /* Explorer loads plugins asynchronously */
        document.onreadystatechange = function () {
            if (document.readyState == 'complete') {
                onVLCPluginReady();
            }
        }
    }

    // ip = getCourtIpByCourtId(now_video);

    $("#channels").change(function () {
        var vlc = getVLC("vlc");
        var now = vlc.input.time;
        channelChange();
        doSetSlider(now);
    });

    $("#videos").change(function () {
        initdown($("#videos").val());
    });

});

function getCaseInfoByIdForToday(caseMap) {
    // $.ajax({
    //     url: r.base_path + "getCaseInfoByUid",
    //     type: "post",
    //     dataType: "json",
    //     data: {
    //         uid: uid,
    //         courtId: now_video
    //     },
    //     success: function (result) {
    //         if(result.status==1){
    //             return ;
    //         }
    var caseInfo = caseMap;
    var archives = caseInfo.archives;
    var caseName = caseInfo.caseName;
    //记录案件名称、案号，并向后台发送点播信息
    record_caseno = archives;
    record_archives = caseName;
    playRecordinfo();
    var subName = "";
    var caseTypeName = caseInfo.casetypeName;
    var judge_user_uid = caseInfo.judgeUserUid;
    var secretary_uid = caseInfo.secretaryUserUid;
    var courtroomName = caseInfo.courtRoomName;
    var statusName = caseInfo.statusName;
    var parties = caseInfo.accuse + " " + caseInfo.accused;
    var startDate = caseInfo.startDate;
    // startDate = startDate.substring(0, startDate.length - 2);
    var planDate = caseInfo.planDate;
    // planDate = planDate.substring(0, planDate.length - 2);
    //
    // var endDate = '未知';
    // if(caseInfo.end_date){
    var endDate = caseInfo.endDate;
    // }
    var caseDesc = caseInfo.casedesc;
    if (caseDesc == null) {
        caseDesc = "";
    }
    var title_text = '&nbsp;' + archives + '——' + caseName;
    if (title_text.length > 50) {
        title_text = title_text.substring(0, 50) + '...';
        // console.log(title_text)
    }

    $("#title").html(title_text);
    var html = ['  <div class="cmp-play-text">',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>案  号：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + archives + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>案件类型：</span>',
        '                            </div>',
        '                            <div class="col-md-3 col-xs-8 text-left">',
        '                                <span>' + caseTypeName + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>案件名称：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + caseName + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>审判长：</span>',
        '                            </div>',
        '                            <div class="col-md-3  col-xs-8 text-left">',
        '                                <span><a id="judge_name" class="white-a">' + (caseInfo.judgeName ? caseInfo.judgeName : '') + '</a></span>',
        '                            </div>',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                            </div>',
        '                            <div class="col-md-3  col-xs-8 text-left">',
        '                            </div>',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>书记员：</span>',
        '                            </div>',
        '                            <div class="col-md-3  col-xs-8 text-left">',
        '                                <span><a id="secretary_name" class="white-a">' + (caseInfo.secretaryName ? caseInfo.secretaryName : '') + '</a></span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>当事人：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + parties + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>开庭地点：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + (courtroomName ? courtroomName : '') + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>排期时间：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + planDate + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>开庭时间：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + startDate + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>闭庭时间：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + endDate + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>庭审状态：</span>',
        '                            </div>',
        '                            <div class="col-md-3 col-xs-8 text-left">',
        '                                <span>' + statusName + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>基本案情：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + caseDesc + '</span>',
        '                            </div>',
        '                        </div>',
        '                    </div>'].join("");
    $("#_court_info").append(html);

    $("#judge_name").attr("href", r.base_path + encodeURI("more/more_review?judge=" + judge_user_uid + "&city=" + now_video + '&court=' + r.court_uid));
    // $("#judge_name").find("span").html('审判长：' + caseInfo.judge_name);

    $("#secretary_name").attr("href", r.base_path + encodeURI("more/more_review?secretary=" + secretary_uid + "&city=" + now_video + '&court=' + r.court_uid));
    // $("#secretary_name").find("span").html('书记员：' + caseInfo.secretary_name);
    $("#loading").hide();
    // },
    // error: function () {
    //     $("#loading").hide();
    // }
    // });
    getInfo();
}

/**
 * 获取点播信息
 */
function getInfo() {
    $.ajax({
        url: r.base_path + "video/selectPlayVideo",
        type: 'post',
        async: false,
        dataType: "json",
        data: {
            planUid: planUid,
            courtUid: now_video
        },
        success: function (result) {
            $("#loading").hide();
            if (result.code == 0) {
                if (!result.data) {
                    alert("没有找到点播信息！");
                    return;
                }
                //result.data赋值给_data 以后操作_data
                _data = eval(result.data);
                $("#data").val(JSON.stringify(_data));
                // console.log(_data);
                var chn = "";
                //构造点播通道select

                $.each(_data, function (i, n) {
                    var fileName = n.fileName;
                    var sxs = fileName.match("(?=[^/]+$).+?(?=[_]+)");
                    // console.log(sxs+n.chn);
                    if (chn.indexOf("[" + n.chn + sxs + "]") == -1) {
                        $("#channels").append("<option value='" + sxs + n.chn + "'>" + n.channelsName + "</option>");
                        chn += "[" + n.chn + sxs + "]";
                    }
                    var r = n.fileName.match(/_\d+/g)[1].substr(1, 6);
                    n.channelsName = r.substring(0, 2) + ":" + r.substring(2, 4);
                    // var chn_ip = filename.substring(filename.lastIndexOf("/"),filename.i);
                });
                //获取url的点播通道号进行选中点播通道的select，如果为空则初始化
                if (channel == null && $("#channels>option").length != 0) {
                    channel = 1;
                } else {
                    $("#channels>option").eq(channel).attr("selected", "selected");
                }
                //调用方法进行构造点播录像select
                initVideoSelect();

                //尝试获取url中点播的视频编号进行选中点播录像select，如果为空则初始化

                if (!videoNum) {
                    videoNum = 0;	//无录像
                }
                $("#videos>option:eq(" + parseInt(videoNum) + ")").attr("selected", "selected");
                //根据点播录像构造vlc的播放列表
                initPlayList();

                //播放文件
                initdown(videoNum);

            } else {
                console.log(result.msg);
            }
        }
    });
}

/**
 * 根据id查询笔录信息
 * @param planUid
 */
function getCourtrecForId() {
    $.post(r.base_path + "video/courtrecForId", {planUid: planUid, courtUid: now_video}, function (result) {
        if (result && result.data) {
            $("#notetext").html(result.data[0]);
            //绑定笔录下载地址--基于http下载
            $("#noteLoad").attr("href", result.data[1]);
        }
    });
}

function channelChange() {
    // console.log("change");
    channel = $("#channels").val();
    videoNum = 0;
    initVideoSelect();
    initPlayList();
    initdown(videoNum);
}
function initdown(num) {
    var vlc = getVLC("vlc");
    if (vlc) {
        //获取当前视频url地址
        now_url = url_data[num];
        vlc.playlist.playItem(num);
        // console.log("href", "http://" + _data[num].url + ":8200/" + _data[num].filename);
    }
}

function down() {
    var down_data = eval($("#data").val());
    //获取当前选中的通道图像
    var name = $("#channels").find("option:selected").text();
    if (name == null && name == "") {
        return;
    }
    //根据图像名称，获取这个通道图像的所有视频
    var channel_data = [];
    for (var index in down_data) {
        if (down_data[index].channelsname == name) {
            //拼接真实下载地址
            //upload_url="http://" + down_data[index].url + ":8200/" + down_data[index].fileName;
            upload_url = "http://" + down_data[index].url + ":8080/" + down_data[index].fileName;
            channel_data.push(upload_url);
        }

    }
    //真实模拟(多视频文件下载)
    if (channel_data["length"] > 0) {
        //测试使用
        //var downloadUrl = ['http://localhost:8080/ssm/videos/2.mp4','http://localhost:8080/ssm/videos/1.mp4'];
        var downloadUrl = channel_data;
        //页面动态生成a标签，模拟用户多个点击事件
        //清空原来下面的a标签
        $("#videosData").empty();
        for (var index in downloadUrl) {
            // 动态创建a标签
            //放在页面上，触发点击事件
            $("#videosData").append("<a download id='" + index + "'href='" + downloadUrl[index] + "'>" + index + "</a>");
            //触发点击事件
            document.getElementById("" + index).click();
        }

    }
}

function initVideoSelect() {
    // console.log(_data);
    var _data_length = _data.length;
    var i = 0;
    //清空select
    $("#videos").html("");
    $.each(_data, function (j, n) {
        var fileName = n.fileName;
        var sxs = fileName.match("(?=[^/]+$).+?(?=[_]+)");
        var temp = $("#channels").val();
        // console.log(sxs+n.chn==temp);
        if (sxs + n.chn == temp) {
            if (i == _data_length - 1) {
                $("#videos").append("<option value=\"" + i + "\">" + n.channelsName + "</option>");
            } else {
                $("#videos").append("<option value=\"" + i + "\">" + n.channelsName + "—" + _data[i + 1].channelsName + "</option>");
            }
            i++;
        }
    });
    $("#videos option:last").html($("#videos option:last").text().substr(0, 5));
}

function initPlayList() {
    var vlc = getVLC("vlc");
    if (vlc) {
        //一言不合先清除下播放列表
        vlc.playlist.items.clear();
        //防止出现意外时初始化视频号
        videoNum = videoNum ? videoNum : 0;
        var options = [":vout-filter=deinterlace", ":deinterlace-mode=linear"];
        $.each(_data, function (i, n) {
            var fileName = n.fileName;
            var sxs = fileName.match("(?=[^/]+$).+?(?=[_]+)");

            var temp = $("#channels").val();
//              console.log(sxs+n.chn + channel,"----sxs",sxs+n.chn,"----temp",temp);
            if (sxs + n.chn == temp) {
                url_data.push("http://" + n.url + ":8200/" + n.fileName);
                vlc.playlist.add("http://" + n.url + ":8200/" + n.fileName, "", options);
                console.log("http://" + n.url + ":8200/" + n.fileName);
            }
        });
//         vlc.playlist.add(r.base_path+'assets/205.64.2.65_20170117_092915_1.mp4');
//         console.log( vlc.playlist.itemCount);
    }
}
function play() {
    $.ajax({
        url: r.base_path + "playConvert",
        type: 'post',
        async: false,
        dataType: "text",
        data: {
            planId: planId,
            courtId: now_video,
            channel: channel,
            videoNum: videoNum
        },
        success: function (result) {
            initdown(result);
        }
    });
}

function getCourtIpByCourtId() {
    $.ajax({
        url: r.base_path + "getCourtIpByCourtId",
        type: "get",
        async: false,
        dataType: "json",
        data: {
            courtId: now_video
        },
        success: function (result) {
            return result.data;
        }
    });
    return '';
}


function getCgfd(uid, cid, courtIp, city) {
    var channel = utils.get_url_param("channel");
    if (!channel) {
        channel = 1;
    }
    $.ajax({
        url: r.base_path + "sys/courtSetting/getCfgInfo",
        type: "post",
        dataType: "json",
        data: {
            cId: cid,
            index: channel,
            ip: courtIp
        },
        success: function (result) {
            if (result != null) {
                var data = result.data;
                var count = 0;
                $(".nav-live").empty();
                for (var key in  data) {
                    $(".nav-live").append('<li role="presentation"><a href="javascript:void(0);"><span>' + key + '</span></a></li>');
                    count = count + 1;
                }
                $(".nav-live").find("li").eq(channel - 1).attr("class", "active");
                var d = $(".nav-live").find("li").eq(channel - 1).find("span").html();
                // console.log(data,d);
                var cha = data[d];//默认显示
                initialise(courtIp, cha);
                $(".nav-live").find("li").click(function () {
                    var inx = $(".nav-live").find("li").index(this) + 1;
                    window.location.href = "living.html?uid=" + uid + "&cid=" + cid + "&flag=1&city=" + now_video + "&channel=" + inx + '&court=' + r.court_id;
                });
            }

        },
        error: function () {
        }
    });
}
function initialise(courtIp, cfg) {
    // console.log("rtsp://" + courtIp + "/" + cfg);
    var vlc = getVLC("vlc");
    if (vlc) {
        vlc.playlist.items.clear();
        while (vlc.playlist.items.count > 0) {
            // clear() may return before the playlist has actually been cleared
            // just wait for it to finish its job
        }
        var options = [":rtsp-tcp"];
        var itemId = vlc.playlist.add("rtsp://" + courtIp + "/" + cfg, "", options);
        if (itemId != -1) {
            vlc.playlist.playItem(itemId);
        }
        else {
            alert("cannot play at the moment !");
        }
    }
}

function doSetSlider(time) {
    var vlc = getVLC("vlc");
    if (vlc) {
        doPlayOrPause();
//        vlc.input.time = (time);
        window.setTimeout(doPlayOrPause, 500);
    }
}


function doPlayOrPause() {
    var vlc = getVLC("vlc");
    if (vlc) {
        vlc.playlist.togglePause();
    }
}


function formatTime(timeVal) {
    if (typeof timeVal != 'number')
        return "-:--:--";
    var timeHour = Math.round(timeVal / 1000);
    var timeSec = timeHour % 60;
    if (timeSec < 10)
        timeSec = '0' + timeSec;
    timeHour = (timeHour - timeSec) / 60;
    var timeMin = timeHour % 60;
    if (timeMin < 10)
        timeMin = '0' + timeMin;
    timeHour = (timeHour - timeMin) / 60;
    if (timeHour > 0)
        return timeHour + ":" + timeMin + ":" + timeSec;
    else
        return timeMin + ":" + timeSec;
}

function onPause() {
}

//抓怕函数
function catch1() {
    //获取当前毫秒数
    var currentTimeMills = doGetPosition();
    //转成秒数
    var time = parseInt(currentTimeMills / 1000);
    //请求后台真真的抓拍功能
    catchImage(time);
}
function doGetPosition() {
    var vlc = getVLC("vlc");
    if (vlc) {
        return vlc.input.time;
    }
}

function formatTime1(value) {

    var theTime = parseInt(value / 1000);// 秒

    var theTime1 = 0;// 分

    var theTime2 = 0;// 小时

    if (theTime > 60) {

        theTime1 = parseInt(theTime / 60);

        theTime = parseInt(theTime % 60);

        if (theTime1 > 60) {

            theTime2 = parseInt(theTime1 / 60);

            theTime1 = parseInt(theTime1 % 60);

        }

    }

    var result = "" + parseInt(theTime) + "秒";

    if (theTime1 > 0) {

        result = "" + parseInt(theTime1) + "分" + result;

    }

    if (theTime2 > 0) {

        result = "" + parseInt(theTime2) + "小时" + result;

    }

    return result;

}
var start = '';
var end = '';
//刷新清空当前数据
$("#startText").val('');
$("#endText").val('');
function start1() {
    var position = doGetPosition();
    start = parseInt(position / 1000);
    $("#startText").val(formatTime1(position));
}
function end1() {
    var position = doGetPosition();
    end = parseInt(position / 1000);
    $("#endText").val(formatTime1(position));
}
function catchImage(time) {
    document.getElementById("catch1").disabled = true;
    $.ajax({
        "type": "post",
        "url": r.base_path + 'catchImage?' + new Date().getTime(),
        "dataType": "json",
        "data": {
            time: time,
            courtId: now_video,
            url: now_url,
            planId: planId,
            videoNum: videoNum
        },
        "success": function (data) {
            var date = new Date();
            var d = JSON.parse(data.data);
            var url = "http://" + location.hostname + ":8080/images/";
            url = url + date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + d.name;
            //先绑定图片到模态框上面
            $("#image").attr("src", url);
            /* 完成拖拽 */
            $("#myModal").draggable({
                cursor: "move"
                //handle: '.modal-header'--指定只有拖拽头部，才能拖拽
            });
            //显示模态框
            $("#myModal").modal("show");
            document.getElementById("catch1").disabled = false;
        },
        "error": function (data) {
            alert("抓拍失败");
            document.getElementById("catch1").disabled = false;
        }
    });
}

//截取函数
function subVideo() {
    //先判断有没有开始跟结束时间
    if (start == null || start == '') {
        alert("请选择视频截取起点");
        return;
    }
    if (end == null || end == '') {
        alert("请选择视频截取终点");
        return;
    }
    if (start > end) {
        start = '';
        end = '';
        alert("截取终点时间不能小于截取起点时间!请重新开始截取");
        return;
    }
    document.getElementById("subVideo").disabled = true;
    $.ajax({
        "type": "post",
        "url": r.base_path + 'subVideo?' + new Date().getTime(),
        "dataType": "json",
        "data": {
            start: start,
            end: end,
            courtId: now_video,
            url: now_url,
            planId: planId,
            videoNum: videoNum
        },
        "success": function (data) {
            alert(data.msg);
            document.getElementById("subVideo").disabled = false;
        },
        "error": function (data) {
            alert("视频截取失败");
            document.getElementById("subVideo").disabled = false;
        }
    });
}


//定时记录点播人员记录
function playRecordinfo() {
    var userName = $.cookie('_username');
    var courtUid = $.cookie('_court_uid');
    console.info(userName, courtUid, record_caseno, record_casename, planUid);
    var data = {
        userName: userName,
        courtId: courtUid,
        planUid: planUid,
        caseNo: record_caseno,
        caseName: record_casename,
        type: "2"
    };
    data = JSON.stringify(data);

    var webSocket =
        new WebSocket('ws://localhost:8080/cmp/recordPlayList');

    webSocket.onerror = function (event) {
        console.info(event);
    };

    webSocket.onopen = function (event) {
        webSocket.send(data);
    };

    webSocket.onmessage = function (event) {
        console.info(event);
    };

    window.onbeforeunload = function () {
        webSocket.close();
    };


//	$.ajax({
//		"type":"post",
//		"url" :r.base_path+'recordPlayList',
//		"dataType":"json",
//		"data": {
//            userName:userName,
//            courtId:courtId,
//            planId:planId,
//            caseNo:record_caseno,
//            caseName:record_casename,
//            type:2,
//            date:date
//        },
//        "success" : function(data) {
//			console.info(data.msg);
//		},
//		"error" : function(data) {
//			console.info(data.msg);
//		}
//	}); 
//	window.setTimeout("playRecordinfo()",30000);
}
